#include "game_thread.h"
#include "game_log.h"
#include <unistd.h>


CGameThread::CGameThread():_thread(0)
{
  pthread_mutex_init(&_mutex, NULL);
  pthread_cond_init(&_cond, NULL);
  _thread = (pthread_t)NULL;
}

CGameThread::~CGameThread(){
  pthread_mutex_destroy(&_mutex);
  pthread_cond_destroy(&_cond);
}

void CGameThread::lock()
{
  pthread_mutex_lock(&_mutex);
}

void CGameThread::unlock()
{
  pthread_mutex_unlock(&_mutex);
}

void CGameThread::sleep(mseconds_t ms)
{
  ::usleep(ms * 1000);
}

void CGameThread::wait(){
  pthread_cond_wait(&_cond,&_mutex);
}

void CGameThread::signal(){
  pthread_cond_signal(&_cond);
}

void CGameThread::broadcast(){
  pthread_cond_broadcast(&_cond);
}

void CGameThread::run(){
  C_LOG("%s","CGameThread::run");
}

thread_t CGameThread::start(){
  return start(NULL);
}

thread_t CGameThread::start(const char* name){
  thread_t thread;
  pthread_create(&thread,NULL,CGame::Thread::__thread_run_cb<CGameThread,&CGameThread::run>,this);
  _thread = thread;

  if(NULL != name){
#if CGAME_TARGET_PLATFORM == CGAME_PLATFORM_LINUX
    pthread_setname_np(thread,name);
#elif CGAME_TARGET_PLATFORM == CGAME_PLATFORM_MAC
    pthread_setname_np(name);
#endif
  }

  return thread;
}

int CGameThread::cancel(thread_t t){
  return pthread_cancel(t);
}

void CGameThread::join(thread_t thread){
  pthread_join(thread,NULL);
}

void CGameThread::join(){
  if((pthread_t)NULL != _thread) {
    join(_thread);
    _thread = (pthread_t)NULL;
  }
}
